﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PlaceHR.Processor.Processor.Salary.Steps
{
    class TaxSalaryStepCalculator : StepCalculatorBase<SalaryProcessorContext, EmployeeSalary>
    {
        public override void Calculate(SalaryProcessorContext salaryProcessorContext, EmployeeSalary employeeSalary)
        {
            if (salaryProcessorContext.IncomeTaxSettings == null || salaryProcessorContext.IncomeTaxSettings.Count < 1)
            {
                return;
            }

            employeeSalary.TaxableSalary = (employeeSalary.BasicSalary ?? 0)
                                                     + (employeeSalary.PositionSalary ?? 0)
                                                     + (employeeSalary.Bonus ?? 0)
                                                     + (employeeSalary.Others ?? 0)
                                                     - (employeeSalary.SickLeave ?? 0)
                                                     - (employeeSalary.UnpaidLeave ?? 0)
                                                     - (employeeSalary.SocialInsuranceIndividual ?? 0)
                                                     - (employeeSalary.HousingFundIndividual ?? 0);

            decimal taxBase = employeeSalary.TaxableSalary.Value - salaryProcessorContext.PersonalIncomeTaxbase;
            if (taxBase <= 0)
            {
                return;
            }

            var currentIncomeTaxSetting = salaryProcessorContext.IncomeTaxSettings.First(p => p.MinNumber.Value <= taxBase && (p.MaxNumber == null || p.MaxNumber.Value >= taxBase));

            employeeSalary.IndividualIncomeTax = taxBase * currentIncomeTaxSetting.Percentage / 100 - currentIncomeTaxSetting.FillBack;
            employeeSalary.NetSalary = (employeeSalary.TaxableSalary ?? 0) - (employeeSalary.IndividualIncomeTax ?? 0) + (employeeSalary.ExpatAllowance ?? 0);
        }

    }
}
